package com.igeek.health.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.igeek.health.config.LoginUser;
import com.igeek.health.constant.MessageConstant;
import com.igeek.health.constant.RedisConstant;
import com.igeek.health.entity.Role;
import com.igeek.health.entity.User;
import com.igeek.health.exception.HealthException;
import com.igeek.health.result.Result;
import com.igeek.health.service.IUserService;
import com.igeek.health.utils.JwtHelper;
import com.igeek.health.vo.PageQueryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/8/28  10:51
 */
@RestController
@RequestMapping("admin/user")
@Api(tags = "管理员的控制层")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @ApiOperation("分页查询管理员列表")
    @GetMapping("/findPage")
    public Result findPage(PageQueryVO pageQueryVO){
        Page<User> page = userService.findPage(pageQueryVO);
        if(CollectionUtil.isNotEmpty(page.getRecords())){
            return new Result(true, "查询管理员成功",page);
        }
        return new Result(false, "查询管理员失败");
    }

    @ApiOperation("根据管理员id查询详情(角色列表)")
    @GetMapping("/findOne/{id}")
    public Result findOne(Integer id){
        List<Role> roleList = userService.findAllRoleByUid(id);
        return new Result(true, "查询管理员详情成功",roleList);
    }

    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        //security进行认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证不通过
        if(ObjectUtil.isEmpty(authenticate)){
            throw new HealthException("用户名或密码输入错误");
        }
        //如果认证通过 获取当前认证信息 存储到redis
        LoginUser principal = (LoginUser)authenticate.getPrincipal();
        User userInfo = principal.getUser();
        Integer id = userInfo.getId();
        //存储的key规则 login::user::1  {username:"",roles:{xxxx}}
        redisTemplate.opsForValue().set(RedisConstant.LOGIN_USER_TOKEN+"::"+id, JSONUtil.toJsonStr(userInfo));

        //生成token数据 返回到前端
        String token = JwtHelper.createToken(id, userInfo.getUsername());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("token",token);
        return new Result(true,MessageConstant.LOGIN_SUCCESS,map);

    }

    @ApiOperation("获取当前登录用户名")
    @GetMapping("/findUserName")
    public Result findUserName(){
        //获取security上下文中获取用户认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser principal = (LoginUser) authentication.getPrincipal();
        String username = principal.getUser().getUsername();
        if(StrUtil.isNotEmpty(username)){
            return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,username);
        }
        return new Result(false,MessageConstant.GET_USERNAME_FAIL);
    }

    @ApiOperation("管理员登出")
    @GetMapping("/logout")
    public Result logout(){
        //获取security上下文中获取用户认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser principal = (LoginUser) authentication.getPrincipal();
        Integer id = principal.getUser().getId();
        //清除缓存中user信息   存储的key规则 login::user::1  {username:"",roles:{xxxx}}
        Boolean flag = redisTemplate.delete(RedisConstant.LOGIN_USER_TOKEN + "::" + id);
        if(flag){
            return new Result(true,"登出成功");
        }
        return new Result(false,"登出失败");
    }














}
